import html2canvas from "/node_modules/.vite/deps/html2canvas.js?v=afd20174";

// import { toPng } from 'html-to-image'
import { native, collectEvent } from "/utils/bridge/index.js";
/**
 * 获取h5链接
 * @param {发给app参数} option
 * @param {埋点参数} trackParams
 */
export function shareUrlCallBack(option, trackParams = {}) {
  native("shareUrl", option, trackParams);
}
/**
 * 分享链接去微信
 * @param {
 *  url: 分享链接
 *  title: 分享标题
 *  icon: 图标
 *  desc: 分享的描述内容
 * } param
 */
export function share(param = {}, trackParams) {
  native(
    "ai_webview_share",
    {
      type: "url",
      url: param.url || "",
      title: param.title || "",
      icon: param.icon || "",
      desc: param.description || "",
      guideLanguage: param.guideLanguage || "好的内容要与朋友们分享噢~",
    },
    trackParams
  );
}
/**
 * 分享图片去微信
 * @param {base图片数据} dataURL
 * @param {埋点参数} trackParams
 */
export function sharePicture(dataURL, trackParams) {
  native(
    "ai_webview_share",
    {
      type: "image",
      image64: dataURL,
      preview: "0",
    },
    trackParams
  );
}
/**
 * 原生分享点击微信或者朋友圈
 * @param {用户id} userId
 * @param {埋点事件id} eventId
 * @param {埋点事件名称} eventTitle
 * @param {收到app点击回调} cb
 * @param {埋点额外参数} param
 */
export function registerShareChannelCallback(
  userId,
  eventId,
  eventTitle,
  cb,
  param = {}
) {
  window.shareChannelFunc = function (result) {
    try {
      if (result) {
        cb && cb();
        // shareChannel：1朋友圈，0好友
        console.log("share image channel", result.shareChannel);
        console.log("@@@@@@@@@@@@@@分享的埋点字段：：：：", param);
        collectEvent({
          eventId, // 事件id
          eventTitle, // 事件名称
          eventTag: "", // 事件标签（暂时保留字段，可以不传）
          parameters: {
            empno: userId || "",
            way: parseInt(result.shareChannel),
            ...param,
          },
        });
      }
    } catch (error) {
      console.log("share ChannelFunc error", error);
    }
  };
}

/**
 * 图片转base64，传给native端，并增加埋点
 * @param {DOM} doc
 * @param {页面实例} vm
 * @param {doc的滑动位置} top
 * @param {埋点数据} trackParams
 */
export function getDataURL(doc, vm, options, trackParams = {}) {
  return new Promise((resolve, reject) => {
    toPng(doc, { quality: 0.01 })
      .then((dt) => {
        // ios下处理两次,解决safari兼容问题
        toPng(doc, {
          width: 300,
          height: 480,
        })
          .then((dataURL) => {
            console.log("dataURL.length", dataURL.length);
            sharePicture(dataURL, trackParams);
            resolve(dataURL);
          })
          .catch((err) => {
            reject(new Error(`背景图片读取错误${err}`));
          });
      })
      .catch((err) => {
        reject(new Error(`背景图片读取错误${err}`));
      });

    //vm.$nextTick(() => {

    // html2canvas(doc, Object.assign({
    //   useCORS: true,
    //   scrollY: 0,
    // },options))
    //   .then(canvas => {
    //     let dataURL = canvas.toDataURL('image/png') // .replace('image/png', 'image/octet-stream')
    //     sharePicture(dataURL, trackParams)
    //     resolve(dataURL)
    //   })
    //   .catch(err => {
    //     reject(new Error(`背景图片读取错误${err}`))
    //   })
    //})
  });
}

/**
 * 图片转base64，传给native端，并增加埋点
 * @param {DOM} doc
 * @param {页面实例} vm
 * @param {doc的滑动位置} top
 * @param {埋点数据} trackParams
 */
export function getDataURL2(doc, vm, options, trackParams = {}) {
  return new Promise((resolve, reject) => {
    html2canvas(
      doc,
      Object.assign(
        {
          useCORS: true,
          scrollY: 0,
        },
        options
      )
    )
      .then((canvas) => {
        let dataURL = canvas.toDataURL("image/png"); // .replace('image/png', 'image/octet-stream')
        sharePicture(dataURL, trackParams);
        resolve(dataURL);
      })
      .catch((err) => {
        reject(new Error(`背景图片读取错误${err}`));
      });
  });
}
/**
 * 保存图片到相册
 * @param {base图片数据} dataURL
 * @param {埋点参数} trackParams
 */
export function savePicture(doc, vm, options, trackParams = {}) {
  return new Promise((resolve, reject) => {
    html2canvas(
      doc,
      Object.assign(
        {
          useCORS: true,
          scrollY: 0,
        },
        options
      )
    )
      .then((canvas) => {
        let dataURL = canvas.toDataURL("image/png"); // .replace('image/png', 'image/octet-stream')
        console.log("savePicture dataURL:"+dataURL)
        native(
          "ai_webview_save_image",
          {
            ret: dataURL,
          },
          trackParams
        );
        resolve(dataURL);
      })
      .catch((err) => {
        reject(new Error(`背景图片读取错误${err}`));
      });
  });
}


/**
 * @description 图片预览（缩放、保存本地、左右滑动查看，8.34版本支持）
 */

import { native } from "/utils/bridge/index.js";
import { compareVersion } from "/utils/index.js";
import { Toast } from "/node_modules/.vite/deps/vant.js?v=afd20174";

export const jumpOpenImage = (urls = [], index = 0) => {
  const version8_34 = compareVersion(202402260);
  if (version8_34 < 0) {
    Toast("请将口袋E更新到最新版本！");
    return;
  }
  return assetAction({
    method: "openImage",
    data: {
      urls,
      index,
    },
  });
};

const assetAction = ({ method, data }) => {
  // console.log("安安", method, data);
  return native("ai_webview_asset_action", {
    method,
    needSave: true,
    androidPreviewVersion: "2.0",
    // moduleName: "安安",
    data,
  });
};

/**
 * 获取抖音或快手授权
 * @param {
*  type: 平台类型
* } param
*/
export async function getPermission(param) {
 return new Promise((resolve, reject) => {
   const onSuccess = (e) => {
     resolve(e);
   };
   const onFail = (e) => {
     resolve("none:" + e);
   };
   setTimeout(() => {
     resolve("method is not exist");
   }, 3000);
   (function waitCordova() {
     if (window.cordova && typeof window.cordova.exec === "function") {
       console.log("cordova is ready");
       window.cordova.exec(onSuccess, onFail, "aiPlugin", "aiPlugin_do_auth", {
         type: param.type || "",
       });
     } else {
       console.log("cordova not ready", window.cordova);
       setTimeout(waitCordova, 30);
     }
   })();
 });
}
